package com.heima.comment.service.impl;

import com.heima.apis.ap_user.IApUserClient;
import com.heima.apis.sensitive.ISensitiveClient;
import com.heima.comment.ParamCheckUtil;
import com.heima.comment.aliyun.GreenTextScan;
import com.heima.comment.service.CommentReplyService;
import com.heima.comment.service.CommentUserService;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jay
 * @date 2022/11/16 14:35:20
 */
@Service
public class CommentReplyServiceImpl implements CommentReplyService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IApUserClient apUserClient;

    @Autowired
    private ISensitiveClient sensitiveClient;

    @Autowired
    private CommentUserService commentUserService;

    @Autowired
    private GreenTextScan greenTextScan;

    @Override
    public ResponseResult save(CommentRepaySaveDto dto) {
        // 1.参数校验
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 1.1 校验被回复的评论是否存在
        Query query = Query.query(Criteria.where("_id").is(dto.getCommentId()));
        // 只查询 reply 字段
        query.fields().include("reply");
        ApComment comment = mongoTemplate.findOne(query, ApComment.class);
        if(comment == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 1.2 检查用户是否存在, 检查评论是否违规
        ApComment reply = ParamCheckUtil.isCheckPasted(dto.getContent(), null, apUserClient, sensitiveClient, greenTextScan);
        if(reply == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMENT_CONTAINS_SENSITIVE);
        }

        // 2.数据准备
        reply.setType((short) 1);
        reply.setChannelId(dto.getCommentId());

        // 3.保存回复
        mongoTemplate.save(reply);

        // 4.被该条回复回复的评论的回复数+1
        Query q = Query.query(Criteria.where("_id").is(dto.getCommentId()));
        Update update = new Update();
        // 评论数+1
        update.set("reply", reply.getReply()+1);
        mongoTemplate.updateFirst(q, update, ApComment.class);

        // 5.返回结果
        return ResponseResult.okResult("回复成功");
    }

    @Override
    public ResponseResult load(CommentRepayDto dto) {

        List<ApComment> comments = null;
        // 1.参数校验
        if(!(dto!=null && dto.getCommentId()!=null
                && dto.getMinDate() != null && dto.getMinDate() > 0)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2.查询
        Query query = new Query();
        query.addCriteria(Criteria.where("channelId").is(dto.getCommentId()));
        query.addCriteria(Criteria.where("type").is(1));
        query.addCriteria(Criteria.where("createdTime").lte(dto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.limit(20);
        comments = mongoTemplate.find(query, ApComment.class);
        comments.forEach(itm -> {
            itm.setOperation(commentUserService.isStared(itm.getId()) ? 0 : 1);
        });

        // 3.返回结果
        return ResponseResult.okResult(comments);
    }

    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        // 1.参数检测
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getCommentRepayId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 检验指定的评论是否存在
        ApComment apComment = mongoTemplate.findById(new ObjectId(dto.getCommentRepayId()), ApComment.class);
        if(apComment == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2. 更新
        HashMap<String, Integer> resultMap = new HashMap<>();
        Update update = new Update();
        if(dto.getOperation() == 0){
            update.set("likes", apComment.getLikes()+1);
            resultMap.put("likes", apComment.getLikes()+1);
            commentUserService.save(dto.getCommentRepayId());
        }
        else if (dto.getOperation() == 1 && apComment.getLikes()>0){
            // likes必须大于0才能减少
            update.set("likes", apComment.getLikes()-1);
            resultMap.put("likes", apComment.getLikes()-1);
            commentUserService.delete(dto.getCommentRepayId());
        }
        Query query = Query.query(Criteria.where("_id").is(new ObjectId(dto.getCommentRepayId())));
        mongoTemplate.updateFirst(query, update, ApComment.class);
        return ResponseResult.okResult(resultMap);
    }
}
